package cn.sf.util;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    public boolean set(String key, String value) {
        boolean flag = false;
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            flag = true;
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    public boolean del(String key) {
        return stringRedisTemplate.delete(key);
    }

    public boolean expire(String key, long time, TimeUnit timeUnit) {
        return stringRedisTemplate.expire(key, time, timeUnit);
    }

    public Set<String> keys(String keyPatterns) {
        return stringRedisTemplate.keys(keyPatterns);
    }

    public boolean setNX(String key, String value) {
        RedisConnection redisConnection = stringRedisTemplate.getConnectionFactory().getConnection();
        return redisConnection.setNX(key.getBytes(), new byte[]{1});
    }

    public boolean exists(String key) {
        RedisConnection redisConnection = stringRedisTemplate.getConnectionFactory().getConnection();
        return redisConnection.exists(key.getBytes());
    }


    /**
     * 将值 value 关联到 key ，并将 key 的过期时间设为 timeout
     *
     * @param key
     * @param value
     * @param timeout 过期时间
     * @param unit    时间单位, 天:TimeUnit.DAYS 小时:TimeUnit.HOURS 分钟:TimeUnit.MINUTES
     *                秒:TimeUnit.SECONDS 毫秒:TimeUnit.MILLISECONDS
     */
    public void setEx(String key, String value, long timeout, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, value, timeout, unit);
    }
}
